package cn.qingyun.gis.modules.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.modules.enterprise.entity.Building;
import cn.qingyun.gis.modules.enterprise.entity.CustomerInfo;
import cn.qingyun.gis.modules.enterprise.entity.Enterprise;
import cn.qingyun.gis.modules.enterprise.entity.dto.EnterpriseTableDataDto;
import cn.qingyun.gis.modules.enterprise.mapper.*;
import cn.qingyun.gis.modules.enterprise.request.EnterpriseRequest;
import cn.qingyun.gis.modules.enterprise.request.OverviewRequest;
import cn.qingyun.gis.modules.enterprise.response.EnterpriseDetailsResponse;
import cn.qingyun.gis.modules.enterprise.response.EnterpriseOverviewResponse;
import cn.qingyun.gis.modules.enterprise.response.EnterpriseTableResponse;
import cn.qingyun.gis.modules.enterprise.service.IBuildingService;
import cn.qingyun.gis.modules.enterprise.service.ICustomerInfoService;
import cn.qingyun.gis.modules.enterprise.service.IEnterpriseService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 企业表 服务实现类
 * </p>
 *
 * @author skb
 * @since 2024-03-29
 */
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements IEnterpriseService {

    @Autowired
    private EnterpriseMapper enterpriseMapper;
    @Autowired
    private IBuildingService buildingService;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private HotelMapper hotelMapper;
    @Autowired
    private StreetShopsMapper streetShopsMapper;
    @Autowired
    private ICustomerInfoService customerInfoService;
    @Autowired
    private OtherMapper otherMapper;

    @Override
    public EnterpriseOverviewResponse getOverviewData(OverviewRequest overviewRequest) {
        String type = overviewRequest.getType();
        String code = overviewRequest.getCode();
        List<String> types = overviewRequest.getTypes();
        EnterpriseOverviewResponse response = new EnterpriseOverviewResponse();
        String column = String.format("%s_code", type);
        try {
            int buildingCount = buildingMapper.getBuildingCount(type, code, types);//获取建筑数
            int buildingClientNum = buildingMapper.getBuildingClientNum(type, code, types);//获取建筑客户数
            EnterpriseOverviewResponse enterpriseOverView = enterpriseMapper.getEnterpriseOverView(column, code , types);
            int enterpriseClientNum = enterpriseMapper.getEnterpriseClientNum(column, code , types);//获取企业客户数
            enterpriseOverView.setTotalNum(enterpriseOverView.getTotalNum() + buildingCount)
                    .setCooperateNum(enterpriseClientNum + buildingClientNum);
            //如果是网格数据概览，需要把酒店和沿街商铺加进来
            if("grid".equals(type)){
                if(types.contains("1")){
                    EnterpriseOverviewResponse hotelOverView = hotelMapper.getHotelOverView(code);
                    int hotelClientNum =hotelMapper.getHotelClientNum(code);
                    enterpriseOverView.setTotalNum(enterpriseOverView.getTotalNum() + hotelOverView.getTotalNum())
                            .setCooperateNum(enterpriseOverView.getCooperateNum() + hotelClientNum)
                            .setCoveredNum(enterpriseOverView.getCoveredNum() + hotelOverView.getCoveredNum());
                }
                if(types.contains("5")){
                    EnterpriseOverviewResponse streetShopsOverView = streetShopsMapper.getStreetShopsOverView(code);
                    int streetShopsClientNum =streetShopsMapper.getStreetShopsClientNum(code);
                    enterpriseOverView.setTotalNum(enterpriseOverView.getTotalNum() + streetShopsOverView.getTotalNum())
                            .setCooperateNum(enterpriseOverView.getCooperateNum() + streetShopsClientNum)
                            .setCoveredNum(enterpriseOverView.getCoveredNum() + streetShopsOverView.getCoveredNum());
                }
                if(types.contains("11")){
                    EnterpriseOverviewResponse otherOverView = otherMapper.getOtherOverView(code);
                    int otherClientNum =otherMapper.getOtherClientNum(code);
                    enterpriseOverView.setTotalNum(enterpriseOverView.getTotalNum() + otherOverView.getTotalNum())
                            .setCooperateNum(enterpriseOverView.getCooperateNum() + otherClientNum)
                            .setCoveredNum(enterpriseOverView.getCoveredNum() + otherOverView.getCoveredNum());
                }
            }
            EnterpriseOverviewResponse buildingOverView = buildingMapper.getBuildingOverView(type, code , types);
            BeanUtils.copyProperties(enterpriseOverView, response);
            response.setBuildingClientNum(buildingClientNum).setAllPortNum(buildingOverView.getAllPortNum()).setUsedPortNum(buildingOverView.getUsedPortNum());
            DecimalFormat decimalFormat = new DecimalFormat("##.#%");
            decimalFormat.setDecimalSeparatorAlwaysShown(false);
            response.setPortOccupancyRate(decimalFormat.format(response.getTotalNum() == 0 ? 0 : response.getUsedPortNum() * 1.0 / response.getTotalNum()))
                    .setPortCoverageRate(decimalFormat.format(response.getTotalNum() == 0 ? 0 : response.getAllPortNum() * 1.0 / response.getTotalNum()))
                    .setPortUtilizationRate(decimalFormat.format(response.getAllPortNum() == 0 ? 0 : response.getUsedPortNum() * 1.0 / response.getAllPortNum()))
                    .setMarketShareRate(decimalFormat.format(response.getTotalNum() == 0 ? 0 : response.getCooperateNum() * 1.0 / response.getTotalNum()));
        } catch (Exception e) {
            throw new CommonException("获取概览数据失败",e);
        }
        return response;
    }

    @Override
    public EnterpriseTableResponse getEnterpriseList(EnterpriseRequest enterpriseRequest) {
        String type = enterpriseRequest.getType();
        String code = enterpriseRequest.getCode();
        int pageSize = enterpriseRequest.getPageSize();
        List<String> types = enterpriseRequest.getTypes();

        EnterpriseTableResponse response = new EnterpriseTableResponse();
        String column = String.format("%s_code", type);
        try {
            List<EnterpriseTableDataDto> buildingList = buildingMapper.getBuildingList(type,code,types);
            List<EnterpriseTableDataDto> enterpriseList = enterpriseMapper.getEnterpriseList(column, code,types);
            enterpriseList.addAll(buildingList);
            if("grid".equals(type)){
                if(types.contains("1")){
                    List<EnterpriseTableDataDto> hotelList = hotelMapper.getHotelList(code);
                    enterpriseList.addAll(hotelList);
                }
                if(types.contains("5")){
                    List<EnterpriseTableDataDto> streetShopsList = streetShopsMapper.getStreetShopsList(code);
                    enterpriseList.addAll(streetShopsList);
                }
                if(types.contains("11")){
                    List<EnterpriseTableDataDto> otherList = otherMapper.getOtherList(code);
                    enterpriseList.addAll(otherList);
                }
            }
            // 对企业列表进行排序
            enterpriseList.sort((o1, o2) -> {
                // 首先比较合作状态
                int cooperationCompare = Integer.compare(o1.getIsCooperate(), o2.getIsCooperate());
                if (cooperationCompare != 0) {
                    return cooperationCompare * -1; // 合作状态不同，按照合作状态排序
                } else {
                    // 合作状态相同，根据flag排序
                    int flagCompare = o1.getFlag().compareTo(o2.getFlag());
                    // 确保"0"（企业）排在"1"（建筑）前面
                    if (flagCompare != 0) {
                        return flagCompare  * -1;
                    } else {
                        return 0; // flag相同，保持原有顺序
                    }
                }
            });

            int totalRecords = enterpriseList.size();
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

            List<List<EnterpriseTableDataDto>> paginatedData = new ArrayList<>();
            for (int i = 0; i < totalPages; i++) {
                int startIndex = i * pageSize;
                int endIndex = Math.min((i + 1) * pageSize, totalRecords);
                List<EnterpriseTableDataDto> pageData = enterpriseList.subList(startIndex, endIndex);
                paginatedData.add(pageData);
            }
            response.setCount(totalRecords).setList(paginatedData);
            return response;
        } catch (Exception e) {
            throw new CommonException("获取企业列表失败");
        }
    }

    @Override
    public List<EnterpriseDetailsResponse> getEnterpriseDetails(String id) {
        List<EnterpriseDetailsResponse> response = new ArrayList<>();
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerInfo::getPoiId, id);
        List<CustomerInfo> customerInfo = customerInfoService.list(queryWrapper);
        if (Objects.nonNull(customerInfo)) {
            response = BeanUtil.copyToList(customerInfo,EnterpriseDetailsResponse.class);
        }
        return response;
    }
}


